<template>
  <el-dialog v-model="dialogVisible" append-to-body class="batch-sign-in-dialog" destroy-on-close title="批量签到" width="800px">
    <div class="batch-sign-in">
      <div class="input-section">
        <el-form label-width="100px" :model="form">
          <el-form-item label="搜索类型">
            <el-radio-group v-model="form.searchType">
              <el-radio label="mobile">手机号</el-radio>
              <el-radio label="name">姓名</el-radio>
            </el-radio-group>
            <span v-if="form.searchText" class="auto-detect-tip">
              <i class="el-icon-magic-stick" />
              已自动识别为{{ form.searchType === 'mobile' ? '手机号' : '姓名' }}格式
            </span>
          </el-form-item>
          <el-form-item :label="form.searchType === 'mobile' ? '手机号' : '姓名'">
            <div class="input-tips">
              <i class="el-icon-info" />
              <span>支持{{ form.searchType === 'mobile' ? '手机号' : '姓名' }}批量输入，每行一个，也可以用逗号分隔</span>
            </div>
            <el-input
              v-model="form.searchText"
              :placeholder="
                form.searchType === 'mobile'
                  ? '例如：\n13800138000\n13900139000\n或 13800138000,13900139000'
                  : '例如：\n张三\n李四\n或 张三,李四'
              "
              :rows="4"
              type="textarea"
              @input="updateInputStats"
              @keydown.enter.ctrl.prevent="handleSearch"
            />
            <div class="input-stats">
              <span>
                当前输入：
                <b>{{ inputStats.valid }}</b>
                个有效{{ form.searchType === 'mobile' ? '号码' : '姓名' }}
              </span>
              <span v-if="inputStats.empty > 0" class="input-stats-warning">（{{ inputStats.empty }} 个空行将被忽略）</span>
              <span v-if="inputStats.valid > 100" class="input-stats-error">超出最大限制（100个）</span>
              <span class="input-tips-keyboard">按 Ctrl + Enter 快速查询</span>
            </div>
          </el-form-item>
        </el-form>
        <div class="button-group">
          <el-button :loading="searching" type="primary" @click="handleSearch">
            <template #icon>
              <i class="el-icon-search" />
            </template>
            查询
          </el-button>
        </div>
      </div>

      <div v-if="searchResults.length > 0" class="result-section">
        <div class="result-header">
          <div class="result-stats">
            <span class="result-stats-item">
              <el-tag effect="plain" type="success">总计 {{ searchResults.length }} 人</el-tag>
            </span>
            <span class="result-stats-item">
              <el-tag v-if="getSignedCount > 0" effect="plain" type="warning">已签到 {{ getSignedCount }} 人</el-tag>
            </span>
            <span class="result-stats-item">
              <el-tag v-if="getUnsignedCount > 0" effect="plain" type="info">未签到 {{ getUnsignedCount }} 人</el-tag>
            </span>
          </div>
          <el-button :disabled="selectedRows.length === 0" :loading="signing" type="primary" @click="handleBatchSignIn">
            <template #icon>
              <i class="el-icon-check" />
            </template>
            签到（已选{{ selectedRows.length }}人）
          </el-button>
        </div>
        <div class="table-container">
          <el-table
            ref="tableRef"
            :data="searchResults"
            highlight-current-row
            :max-height="300"
            :row-class-name="tableRowClassName"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column :selectable="(row) => !row.isCheck" type="selection" width="55" />
            <el-table-column label="姓名" min-width="100" prop="name" />
            <el-table-column label="手机号" min-width="120" prop="mobile" />
            <el-table-column label="职务" min-width="120">
              <template #default="{ row }">
                <el-tag v-for="post in getPostNames(row)" :key="post" class="mx-1" effect="plain" size="small">
                  {{ post }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="签到状态" min-width="100" prop="isCheck">
              <template #default="{ row }">
                <el-tag effect="plain" :type="row.isCheck ? 'success' : 'info'">
                  {{ row.isCheck ? '已签到' : '未签到' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div v-if="notFoundItems.length > 0" class="not-found-section">
        <div class="not-found-title">
          <i class="el-icon-warning-outline" />
          未找到以下{{ form.searchType === 'mobile' ? '手机号' : '姓名' }}：
        </div>
        <div class="not-found-content">
          {{ notFoundItems.join('、') }}
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { Person } from '../types'
import Public from '/@/api/public'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}>()

const form = ref({
  searchType: 'mobile',
  searchText: '',
})

const searching = ref(false)
const signing = ref(false)
const searchResults = ref<Person[]>([])
const notFoundItems = ref<string[]>([])
const selectedRows = ref<Person[]>([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const getPostNames = (row: Person) => {
  if (!row.userInfo?.postsMiddle) return []
  return Array.isArray(row.userInfo.postsMiddle) ? row.userInfo.postsMiddle.map((item: any) => item.posts?.name || '-') : []
}

const handleSelectionChange = (rows: Person[]) => {
  selectedRows.value = rows
}

const inputStats = ref({
  total: 0,
  empty: 0,
  valid: 0,
})

const updateInputStats = () => {
  const lines = form.value.searchText.split(/[\n,，]+/)
  const validLines = lines.map((line) => line.trim()).filter(Boolean)

  // 自动识别输入类型
  if (validLines.length > 0) {
    const isMobileNumber = validLines.every((line) => /^1[3-9]\d{9}$/.test(line))
    if (isMobileNumber) {
      form.value.searchType = 'mobile'
    } else {
      const isLikelyName = validLines.every((line) => {
        // 检查是否像名字（2-4个汉字）
        return /^[\u4e00-\u9fa5]{2,4}$/.test(line)
      })
      if (isLikelyName) {
        form.value.searchType = 'name'
      }
    }
  }

  inputStats.value = {
    total: lines.length,
    empty: lines.length - validLines.length,
    valid: validLines.length,
  }
}

const parseSearchText = () => {
  return form.value.searchText
    .split(/[\n,，]+/)
    .map((item) => item.trim())
    .filter(Boolean)
}

const handleSearch = async () => {
  const items = parseSearchText()
  if (items.length === 0) {
    ElMessage.warning('请输入搜索内容')
    return
  }

  if (items.length > 100) {
    ElMessage.warning('单次最多支持100个搜索项')
    return
  }

  searching.value = true
  try {
    const activityId = localStorage.getItem('hongyouActId')
    const params = {
      activityId,
      [form.value.searchType]: items.join(','),
    }
    const response = await Public.getDetailApi({
      url: '/api/player/batch-name-query',
      params,
    })

    if (response.code === 0) {
      searchResults.value = response.result || []

      const foundItems = new Set(searchResults.value.map((item) => (form.value.searchType === 'mobile' ? item.mobile : item.name)))
      notFoundItems.value = items.filter((item) => !foundItems.has(item))

      if (searchResults.value.length === 0) {
        ElMessage.warning('未找到任何匹配结果')
      } else {
        ElMessage.success(
          `找到 ${searchResults.value.length} 条记录${notFoundItems.value.length > 0 ? `，${notFoundItems.value.length} 条未匹配` : ''}`
        )
      }
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    searching.value = false
  }
}

const handleBatchSignIn = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要签到的人员')
    return
  }

  signing.value = true
  const activityId = localStorage.getItem('hongyouActId')

  try {
    const userIds = selectedRows.value.map((person) => person.userId).join(',')
    const response = await Public.signInApi({
      url: '/api/checkins',
      data: {
        userId: userIds,
        activityId,
        checkType: '人工',
      },
    })

    if (response.code === 0) {
      ElMessage.success(`签到完成：${selectedRows.value.length}人`)
      emit('refresh')
      dialogVisible.value = false
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    signing.value = false
  }
}

const getSignedCount = computed(() => searchResults.value.filter((item) => item.isCheck).length)
const getUnsignedCount = computed(() => searchResults.value.filter((item) => !item.isCheck).length)

const tableRowClassName = ({ row }: { row: Person }) => {
  if (row.isCheck) {
    return 'row-signed'
  }
  return ''
}
</script>

<style scoped>
.batch-sign-in {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-section {
  border-bottom: 1px solid #eee;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.result-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.not-found-section {
  background-color: #fff9f9;
  padding: 12px;
  border-radius: 4px;
  margin-top: 8px;
}

.not-found-title {
  color: #f56c6c;
  margin-bottom: 8px;
  font-weight: 500;
}

.not-found-content {
  color: #666;
  line-height: 1.5;
  word-break: break-all;
}

.mx-1 {
  margin: 0 4px;
}

.input-stats {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 8px;
}

.input-stats-warning {
  color: #e6a23c;
}

.input-stats-error {
  color: #f56c6c;
}

.input-tips {
  margin-bottom: 8px;
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.input-tips-keyboard {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}

.result-stats {
  display: flex;
  gap: 12px;
  align-items: center;
}

.result-stats-item {
  display: flex;
  align-items: center;
}

:deep(.row-signed) {
  background-color: #f0f9eb;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-tag) {
  border-radius: 4px;
}

.not-found-title {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 优化输入框样式 */
:deep(.el-textarea__inner) {
  font-family: monospace;
  line-height: 1.6;
}

/* 优化表格hover效果 */
:deep(.el-table__row:hover) {
  cursor: pointer;
}

/* 添加过渡动画 */
.result-section,
.not-found-section {
  transition: all 0.3s ease;
}

.table-container {
  margin: 8px 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.batch-sign-in-dialog :deep(.el-dialog) {
  margin-top: 5vh !important;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

/* 优化滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  border-radius: 3px;
  background: #dcdfe6;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  border-radius: 3px;
  background: #f5f7fa;
}

.auto-detect-tip {
  margin-left: 12px;
  font-size: 12px;
  color: #67c23a;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.auto-detect-tip i {
  font-size: 14px;
}
</style>
